package com.atguigu.springcloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

/**
 * @Author: lihan
 * @Date : 2021/12/9- 12
 * @DESCRIPTION: com.atguigu.springcloud.service
 * @version: 1.0
 */
@Service
public class PaymentService {

    public String paymentInfo_OK(Integer id){

        return "线程池："+ Thread.currentThread().getName()+ "  paymentInfo_OK: "+id+"\t" +"哈哈";
    }

    @HystrixCommand(fallbackMethod = "paymentInfoTimeoutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    public String paymentInfo_TimeOut(Integer id){
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        return "线程池："+ Thread.currentThread().getName()+ "  paymentTimeOut: "+id+"\t" +"超时";
    }


    public String paymentInfoTimeoutHandler(Integer id){
        return "线程池："+ Thread.currentThread().getName()+ "  paymentInfoTimeoutHandler: "+id+"\t";
    }

    //服务熔断

    @HystrixCommand(fallbackMethod = "paymentCircuitBreakerFallback", commandProperties = {
            // 开启断路器
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
            // 请求次数
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
            // 时间窗口期
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
            // 失败率
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")
    })
    public String paymentCircuitBreaker(@PathVariable("id") Integer id) {
        if (id < 0) {
            throw new RuntimeException("ID 不能为负数");
        }
        return "正常访问： " + IdUtil.simpleUUID();
    }

    public String paymentCircuitBreakerFallback(@PathVariable("id")Integer id) {
        return Thread.currentThread().getName() + "ID 不能为负数 熔断服务降级FallBack!" + id;
    }

        }
